/*
 * $Id: api_getncpus.c 50 2009-02-10 05:48:05Z hyunghwan.chung $
 *
   Copyright 2005-2009 Chung, Hyung-Hwan.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an  BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */

#include <xp/sys/api.h>

#if defined(_WIN32)
	#include <pdh.h>
#else
	#include <unistd.h>

	#ifdef HAVE_SYS_SYSINFO_H
	#include <sys/sysinfo.h>
	#endif
	#ifdef HAVE_SYS_SYSCTL_H
	#include <sys/sysctl.h>
	#endif
	#ifdef HAVE_KVM_H
	#include <kvm.h>
	#endif
	#ifdef HAVE_FCNTL_H
	#include <fcntl.h>
	#endif

#endif

int xp_getncpus (xp_size_t* ncpus)
{
#if defined(_WIN32)
	SYSTEM_INFO sys_info;
	GetSystemInfo (&sys_info);
	*ncpus = sys_info.dwNumberOfProcessors;
	return 0;
#elif defined(_SC_NPROCESSORS_CONF)
	/* may use _SC_NPROCESSORS_ONLN */
	long v = sysconf (_SC_NPROCESSORS_CONF);
	if (v == -1) return -1;
	*ncpus = (xp_size_t)v;
	return 0;
#elif defined(CTL_HW) && defined(HW_NCPU)
	/* BSDs */
	/* may use HW_AVAILCPU instead of HW_NCPU */
	int mib[2] = { CTL_HW, HW_NCPU };
	xp_size_t len = XP_SIZEOF(*ncpus);
	return sysctl (mib, 2, ncpus, len, NULL, 0);	
#else
	#error **** UNSUPPORTED PLATFORM ****
#endif
}

